import Router from 'koa-router'
import os from 'os'
import fs from 'fs'
import requests from 'request'
import path from 'path'
import cheerio from 'cheerio'

const { URL } = require('url');

let get = url => {
    let promise = new Promise((resolve, reject) => {
        requests(url, (err, response, body) => {
            if (err) {
                reject(err)
            } else {
                resolve(response.body)
            }
        })
    });
    return promise
}

let post = (url, formData) => {
    return new Promise((resolve, reject) => {
        requests.post({url, form: formData}, (err, response, body) => {
            if (err) {
                reject(err)
            } else {
                resolve(response.body)
            }
        })
    })
}

const router = Router()

/*
 * @request.body image_url
 * @request.body dir
 */
router.get('/download/image', async ({query, request, response}, next) => {
    let image_url  = query.image_url;
    let host = new URL(image_url).host;
    // console.info('image_url', image_url);
    let directory  = query.dir || '';
    // console.info('directory', directory);
    let image_root = path.join(__dirname, '../image');
    // console.info('image_root', image_root);
    let image_dir  = path.join(image_root, directory);
    // console.info('image_dir', image_dir);
    let image_name = path.basename(image_url);
    // console.info('image_name', image_name);
    let image_path = path.join(image_dir, image_name);
    // console.info('image_path', image_path);
    let statRoot = null;
    let statDir = null;
    let isExistRoot = true;
    let isExistDir = true;
    try {
        statRoot = fs.statSync(image_root);
    } catch (error) {
        isExistRoot = false;
    }
    try {
        statDir = fs.statSync(image_dir);
    } catch (error) {
        isExistDir = false;
    }
    if (!isExistRoot) {
        fs.mkdirSync(image_root);
    }
    if (!isExistDir) {
        fs.mkdirSync(image_dir);
    }
    let save_image = fs.createWriteStream(image_path)
    requests.head(image_url, function(err, res, body){
        let image = requests({
            url: image_url,
            headers: {
                'User-Agent': 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25'
            }
        }).pipe(save_image)
    })
})
/**
 * @query url        爬取地址
 * @query selector   爬取位置css选择器
 * @query attr       爬取的属性
 */
router.get('/crawl/data', async ({request, response, query}, next) => {
    let body = query
    let pageUrl = body.url;
    let page = await get(pageUrl);
    let $ = cheerio.load(page);
    let selector = body.selector || 'img';
    let attribute = body.attr || 'src';
    let results = [];
    $(selector).each((index, item) => {
        let result = $(item).attr(attribute)
        results.push(result)
    });
    response.body = results.filter(item => item)
});

export default router
